/**
 * 
 */
package io.dora.zk;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.io.FileUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;

/**
 * @author zhaohongbo
 *
 */
public class CuratorTest {
	
	private CuratorFramework zkClient;
	
	ExecutorService pool = Executors.newFixedThreadPool(2);
	
	public CuratorTest() {
		zkClient = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181").retryPolicy(new RetryNTimes(2000,20000)).build();
		zkClient.start();
	}
	
	public void setData(String node, String data) {
		try {
			Stat stat = zkClient.checkExists().forPath(node);
			if (stat == null) {
				zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE).forPath(node);
			}
			zkClient.setData().forPath(node, data.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String getData(String node) {
		try {
			byte[] b = zkClient.getData().forPath(node);
			System.out.println(new String(b));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public void setNodeListener(final String node) {
		final NodeCache nodeCache = new NodeCache(zkClient, node);
		try {
			nodeCache.start(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		nodeCache.getListenable().addListener(new NodeCacheListener () {
			public void nodeChanged() throws Exception {
				System.out.println("----------------->" + node + " is change");
				System.out.println("-----------------> new data " + getData(node));
			}
		}, pool);
	}

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		CuratorTest c = new CuratorTest();
		/*
		c.getData("/jshop-cx/com.jd.jshop.rpc.face.HelloRpc");
		c.setData("/ab/cd", "Hello Curator222");
		c.getData("/ab/cd");
		c.setNodeListener("/ab/cd");
		*/
		
		//c.setData("/jshop-cx/jshop", "111");
		try {
			//String p = FileUtils.readFileToString(new File("d:/jdbc.properties"));
			//c.setData("/jshop-cx/jshop", p);
			System.out.println(c.getData("/jshop-cx/jshop/config-db/yf-rw"));
			c.setNodeListener("/jshop-cx/jshop/config-db/yf-rw");
			Thread.sleep(100000000000000L);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
